/**axios封装
 * 请求拦截、相应拦截、错误统一处理
 */
import axios from 'axios'
import Qs from 'qs'
import tool from '../utils/tool'
import storeAxios from '../utils/storeAxios'
// 需使用require
import config from '../../config/envDefault'
import frequencyMap from './frequency'
/**
 * 获取url参数
 * @param {string} query url参数
 * @return {object} url参数对象
 * @example
 * util.getQuery('lechebang.com?key=value&city=3')
 * util.getQuery(location.search)
 * // 如果参数里面有url或者中文，请先自行先encodeURIComponent字符串
 */
function getQuery(query) {
  var ret = {}
  var searchReg = /([^&=?]+)=([^&]+)/g
  var name, value
  let match = searchReg.exec(query)
  while (match) {
    name = match[1]
    value = match[2]
    ret[name] = decodeURIComponent(value)
    match = searchReg.exec(query)
  }
  return ret
}

let options = {
  baseURL: 'http://139.9.210.43:5000',
  timeout: 6000
}

//服务端调用
// if (typeof window !== 'object') {
//   if (config.serverApiUrl.host) {
//     options.headers = { Host: config.serverApiUrl.host }
//   }
// }

//post请求头
axios.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded;charset=UTF-8'
let instance = axios.create(options)


// 响应拦截器，只在客户端响应
if (typeof window === 'object') {
  window.frequencyMap = frequencyMap
  instance.interceptors.response.use(
    response => {
      let {
        status,
        data,
        config: { url, data: configData, params: configParams }
      } = response
      if (status === 200) {
        // 调接口时传参：loginType （登陆方式）：1：跳转登录页登录；2:弹窗登录；
        if (+data.errcode === 1001) {
          //未登录
          if (
            (configData && +getQuery(configData).loginType === 2) ||
            (configParams && +configParams.loginType === 2)
          ) {
            //弹窗登录
            // 触发自定义的事件，去显示登录弹窗，事件监听在app.vue文件里
            tool.showLoginDialog()
          }
        }
        return Promise.resolve(response)
      } else {
        return Promise.reject(response)
      }
    },
    // 服务器状态码不是200的情况
    error => {
      if (error.response.status) {
        return Promise.reject(error.response)
      }
    }
  )
}

const http = {
  get(url, params = {}) {
    console.log(888,url,params);
    return new Promise((resolve, reject) => {
      instance
        .get(url, {
          params: { from: 'web', channel: 'web', devtype: 'web', platform_type: 'web', ...params, t: Date.now() }
        })
        .then(res => {
          console.log(777,res)
          resolve(res.data)
        })
        .catch(err => {
          console.log(666,err);
          reject(err.data)
        })
    })
  },
  head(url, params = {}) {
    // 表示没有缓存，则发送接口请求
    return new Promise((resolve, reject) => {
      instance
        .head(url, {
          params: { ...params, t: Date.now() }
        })
        .then(res => {
          // 获取接口 + 接口请求参数的内存值
          resolve(res.data)
        })
        .catch(err => {
          reject(err.data)
        })
    })
  },
  post(url, params = {}, option = {}) {
    if (typeof window === 'object') {
      if (window.frequencyMap.checkUrl(url, 'post')) {
        tool.showApiLimitDialog()
        return Promise.reject({
          errcode: 9999,
          errmsg: '请求频率过高，请刷新页面重试！'
        })
      }
    }
    return new Promise((resolve, reject) => {
      instance
        .post(url, Qs.stringify(params), option)
        .then(res => {
          resolve(res.data)
        })
        .catch(err => {
          reject(err.data)
        })
    })
  },
  delete(url, params = {}) {
    return new Promise((resolve, reject) => {
      instance
        .delete(url, { data: params })
        .then(res => {
          resolve(res.data)
        })
        .catch(err => {
          reject(err.data)
        })
    })
  }
}
// 服务器端改写http.get和http.post
if (typeof window !== 'object') {

  http.get = function(url, params = {}) {
    console.log(111,url,params);
    // 默认都缓存
    let isServiceCache = tool.isObject(params) && params.isServiceCache === false ? false : true

    if (isServiceCache) {
      // 先判断是否有缓存
      let cacheData = storeAxios.getItem(url, params)
      if (cacheData) {
        return Promise.resolve(cacheData)
      }
    }
    console.log(444);
    return new Promise((resolve, reject) => {
      instance
        .get(url, { params: { ...params, t: Date.now() } })
        .then(res => {
          console.log(222,res.data);
          // if (+res.data.errcode === 0 && isServiceCache) {
          //   // 更新本地缓存
          //   storeAxios.setItem(url, res.data, params)
          // }     
          resolve(res.data)
        })
        .catch(err => {
          console.log(333,err);
          reject(err.data)
        })
    })
  }

  http.post = function(url, params = {}, option = {}) {
    return new Promise((resolve, reject) => {
      instance
        .post(url, Qs.stringify(params), option)
        .then(res => {
          resolve(res.data)
        })
        .catch(err => {
          reject(err.data)
        })
    })
  }
}

export default http
